package com.ciwong.epaper.modules.scan.dao;

import android.app.Activity;
import android.text.TextUtils;
import android.util.Log;

import com.ciwong.epaper.R;
import com.ciwong.epaper.application.EApplication;
import com.ciwong.epaper.modules.epaper.bean.EpaperInfo;
import com.ciwong.epaper.modules.epaper.util.EpaperJumpManager;
import com.ciwong.epaper.modules.scan.bean.EpaperQRInfo;
import com.ciwong.epaper.modules.scan.bean.QrBook;
import com.ciwong.epaper.modules.scan.bean.Resourse;
import com.ciwong.epaper.modules.scan.util.ScanJumpManager;
import com.ciwong.epaper.util.BaseExtCallBack;
import com.ciwong.epaper.util.FileUtil;
import com.ciwong.epaper.util.IntentValue;
import com.ciwong.epaper.util.download.DownLoadInfo;
import com.ciwong.epaper.util.download.DownloadStatus;
import com.ciwong.libs.utils.CWLog;
import com.ciwong.libs.widget.CWToast;
import com.ciwong.mobilelib.i.BaseCallBack;

import java.util.ArrayList;
import java.util.List;

/**
 * 扫一扫 相关业务Dao
 *
 * @author bin
 * @version ciwong v.1.0 2015/7/23 20:09
 * @since ciwong v.1.0
 */
public class ScanDao {
    private static ScanDao instance;

    private ScanDao() {
    }

    /**
     * 获取唯一实例
     *
     * @return 唯一实例
     */
    public static ScanDao getInstance() {
        if (instance == null) {
            syncInit();
        }
        return instance;
    }

    /**
     * 实例化对象
     */
    private static synchronized void syncInit() {
        if (instance == null) {
            instance = new ScanDao();
        }
    }

    //获取书籍信息跳转书籍详情页
    public void getBookInfo(final Activity activity, final String producted) {
        ScanRequest.getBookInfo(producted, new BaseExtCallBack(activity, EApplication.getInstance().getUserInfoBase().getUserId() + "") {
            @Override
            public void failed(int errorCode, Object data) {
                super.failed(errorCode, data);
                ScanJumpManager.jumpNewspaperQRInfo(R.string.go_back, activity, null, null, true, null);
            }

            @Override
            public void failed(Object data) {
                super.failed(data);
                ScanJumpManager.jumpNewspaperQRInfo(R.string.go_back, activity, null, null, true, null);
                CWToast.makeText(activity, String.valueOf(data),
                        CWToast.LENGTH_LONG).show();
            }

            @Override
            public void success(Object data) {
                QrBook qrBook = (QrBook) data;
                if (qrBook != null) {
                    //判断APP品牌下有无匹配资源
                    getQRandBrandResouurceInfo(EApplication.BRAND_ID, producted, activity, null, null, qrBook);
                }

            }
        });
    }

    /**
     * 扫描结果无需验证，直接展示
     *
     * @param activity
     * @param resultStr
     */
    public void newspaperQRInfoLogicPreView(final Activity activity,
                                            final String resultStr) {
        hasNoDownloadPreView(activity, resultStr);
    }

    /**
     * 扫码 下载 zip
     *
     * @param activity
     * @param resultStr
     */
    public void newspaperQRInfoLogic(final Activity activity,
                                     final String resultStr) {
        hasNoDownload(activity, resultStr);
    }


    /**
     * 不验证 ，直接展示
     *
     * @param activity
     * @param actionStr
     */
    private void hasNoDownloadPreView(final Activity activity, String actionStr) {
        //请求离线包信息
        getQRResourceInfo(actionStr, new BaseExtCallBack(activity, EApplication.getInstance().getUserInfoBase().getUserId() + "") {
            @Override
            public void failed(Object data) {
                CWLog.d("Scan",data.toString()+":");
                CWToast.makeText(activity, "网络异常", CWToast.LENGTH_LONG).show();
            }

            @Override
            public void failed(int errorCode, Object data) {
                CWLog.d("Scan",data.toString()+" : "+errorCode);
                //未找到资源的时候　显示无匹配资源
                CWToast.makeText(activity, "无匹配资源", CWToast.LENGTH_LONG).show();
                if (errorCode == 5001) {
                    ScanJumpManager.jumpNewspaperQRInfo(R.string.go_back,
                            activity, null, null, true, null);
                } else {
                    super.failed(errorCode, data);
                }
            }

            @Override
            public void success(Object data) {
                try {
                    CWLog.d("Scan",data.toString());
                    EpaperQRInfo qrInfo = (EpaperQRInfo) data;

                    ArrayList<DownLoadInfo> downLoadInfos=new ArrayList<DownLoadInfo>();
                    if(qrInfo!=null){
                        if(qrInfo.getcType()==1){
                            ArrayList<Resourse> resourseArrayList=(ArrayList<Resourse>)qrInfo.getResourceList();
                            for (Resourse r:resourseArrayList)
                            {
                                DownLoadInfo downLoadInfo = new DownLoadInfo();
                                downLoadInfo.setIsPublish(qrInfo.getIsPublish());
                                downLoadInfo.setBookId(qrInfo.getPackageId());
                                downLoadInfo.setBookName(qrInfo.getPackageName());
                                downLoadInfo.setChapterId(qrInfo.getcId());
                                downLoadInfo.setChapterName(qrInfo.getCodeName());
                                downLoadInfo.setIconUrl(qrInfo.getPackageCover());
                                downLoadInfo.setSubjectId(qrInfo.getSubjectId());
                                downLoadInfo.setType(qrInfo.getcType());
                                String fileSize;
                                downLoadInfo.setUrl(r.getResourceUrl());
                                downLoadInfo.setSavePath(
                                        FileUtil.getSavePathByUrl(activity, r.getResourceUrl()));
                                fileSize = r.getFileSize();
                                downLoadInfo.setModuleName(r.getModuleName());
                                downLoadInfo.setResourceName(r.getResourceName());
                                downLoadInfo.setResourceType(r.getResourceType());
                                downLoadInfo.setModuleId(r.getModuleId()+"");
                                downLoadInfo.setVersionId(r.getVersionId());


                                downLoadInfo.setKey(qrInfo.getUrl() + ",");
                                downLoadInfo.setStatus(DownloadStatus.STATUS_NORMAL);

                                if (!TextUtils.isEmpty(fileSize) && fileSize.contains(" ")) {
                                    downLoadInfo.setSize(fileSize.split(" ")[0]);
                                }
                                downLoadInfos.add(downLoadInfo);

                            }
                        }else {

                            DownLoadInfo downLoadInfo = new DownLoadInfo();
                            downLoadInfo.setIsPublish(qrInfo.getIsPublish());
                            downLoadInfo.setBookId(qrInfo.getPackageId());
                            downLoadInfo.setBookName(qrInfo.getPackageName());
                            downLoadInfo.setChapterId(qrInfo.getcId());
                            downLoadInfo.setChapterName(qrInfo.getCodeName());
                            downLoadInfo.setIconUrl(qrInfo.getPackageCover());
                            downLoadInfo.setSubjectId(qrInfo.getSubjectId());
                            downLoadInfo.setType(qrInfo.getcType());
                            String fileSize;

                            downLoadInfo.setUrl(qrInfo.getDownLoadUrl());
                            downLoadInfo.setSavePath(
                                    FileUtil.getSavePathByUrl(activity, qrInfo.getDownLoadUrl()));
                            fileSize = qrInfo.getFileSize();


                            downLoadInfo.setKey(qrInfo.getUrl() + ",");
                            downLoadInfo.setStatus(DownloadStatus.STATUS_NORMAL);

                            if (!TextUtils.isEmpty(fileSize) && fileSize.contains(" ")) {
                                downLoadInfo.setSize(fileSize.split(" ")[0]);
                            }
                            downLoadInfos.add(downLoadInfo);

                        }


                    }

                    ScanJumpManager.jumpToNewTypeQrDetailAct(R.string.go_back, activity, downLoadInfos,  true);

                } catch (Exception e) {
                    e.printStackTrace();
                    Log.e("Scan",e.toString());
                    CWToast.makeText(activity, "无效数据", CWToast.LENGTH_LONG)
                            .show();
                }
            }
        });
    }

    private void hasNoDownload(final Activity activity, String actionStr) {


        //请求离线包信息
        getQRResourceInfo(actionStr, new BaseExtCallBack(activity, EApplication.getInstance().getUserInfoBase().getUserId() + "") {
            @Override
            public void failed(Object data) {
                CWLog.d("Scan failed",data.toString());
                CWToast.makeText(activity, "网络异常", CWToast.LENGTH_LONG).show();
            }

            @Override
            public void failed(int errorCode, Object data) {
                //未找到资源的时候　显示无匹配资源
                CWLog.d("Scan failed",data.toString()+errorCode);
                ScanJumpManager.jumpNewspaperQRInfo(R.string.go_back,
                        activity, null, null, true, null);
            }

            @Override
            public void success(Object data) {
                try {
                    CWLog.d("Scan success",data.toString());
                    EpaperQRInfo qrInfo = (EpaperQRInfo) data;

                    ArrayList<DownLoadInfo> downLoadInfos=new ArrayList<DownLoadInfo>();
                    if(qrInfo!=null){
                        if(qrInfo.getcType()==1){
                            ArrayList<Resourse> resourseArrayList=(ArrayList<Resourse>)qrInfo.getResourceList();
                            for (Resourse r:resourseArrayList)
                            {
                                DownLoadInfo downLoadInfo = new DownLoadInfo();
                                downLoadInfo.setIsPublish(qrInfo.getIsPublish());
                                downLoadInfo.setBookId(qrInfo.getPackageId());
                                downLoadInfo.setBookName(qrInfo.getPackageName());
                                downLoadInfo.setChapterId(qrInfo.getcId());
                                downLoadInfo.setChapterName(qrInfo.getCodeName());
                                downLoadInfo.setIconUrl(qrInfo.getPackageCover());
                                downLoadInfo.setSubjectId(qrInfo.getSubjectId());
                                downLoadInfo.setType(qrInfo.getcType());
                                String fileSize;
                                    downLoadInfo.setUrl(r.getResourceUrl());
                                    downLoadInfo.setSavePath(
                                            FileUtil.getSavePathByUrl(activity, r.getResourceUrl()));
                                    fileSize = r.getFileSize();
                                    downLoadInfo.setModuleName(r.getModuleName());
                                    downLoadInfo.setResourceName(r.getResourceName());
                                    downLoadInfo.setResourceType(r.getResourceType());
                                    downLoadInfo.setModuleId(r.getModuleId()+"");
                                    downLoadInfo.setVersionId(r.getVersionId());


                                downLoadInfo.setKey(qrInfo.getUrl() + ",");
                                downLoadInfo.setStatus(DownloadStatus.STATUS_NORMAL);

                                if (!TextUtils.isEmpty(fileSize) && fileSize.contains(" ")) {
                                    downLoadInfo.setSize(fileSize.split(" ")[0]);
                                }
                                downLoadInfos.add(downLoadInfo);

                            }
                        }else {

                            DownLoadInfo downLoadInfo = new DownLoadInfo();
                            downLoadInfo.setIsPublish(qrInfo.getIsPublish());
                            downLoadInfo.setBookId(qrInfo.getPackageId());
                            downLoadInfo.setBookName(qrInfo.getPackageName());
                            downLoadInfo.setChapterId(qrInfo.getcId());
                            downLoadInfo.setChapterName(qrInfo.getCodeName());
                            downLoadInfo.setIconUrl(qrInfo.getPackageCover());
                            downLoadInfo.setSubjectId(qrInfo.getSubjectId());
                            downLoadInfo.setType(qrInfo.getcType());
                            String fileSize;

                            downLoadInfo.setUrl(qrInfo.getDownLoadUrl());
                            downLoadInfo.setSavePath(
                                        FileUtil.getSavePathByUrl(activity, qrInfo.getDownLoadUrl()));
                            fileSize = qrInfo.getFileSize();


                            downLoadInfo.setKey(qrInfo.getUrl() + ",");
                            downLoadInfo.setStatus(DownloadStatus.STATUS_NORMAL);

                            if (!TextUtils.isEmpty(fileSize) && fileSize.contains(" ")) {
                                downLoadInfo.setSize(fileSize.split(" ")[0]);
                            }
                            downLoadInfos.add(downLoadInfo);

                        }


                    }
                    //判断APP品牌下有无匹配资源
                    getQRandBrandResouurceInfo(EApplication.BRAND_ID, qrInfo.getPackageId(), activity, downLoadInfos, qrInfo, null);
                } catch (Exception e) {
                    e.printStackTrace();
                    Log.e("Scan",e.toString());
                    CWToast.makeText(activity, "无效数据", CWToast.LENGTH_LONG).show();
                }
            }
        });
    }

    /**
     * 根据二维码获取离线包信息
     *
     * @param url      URL地址
     * @param callBack 回调
     */
    public void getQRResourceInfo(String url, BaseCallBack callBack) {
        ScanRequest.getQRResourceInfo(url, callBack);
    }

    /**
     * 判断资源和品牌的匹配情况
     *
     * @param brandId
     * @param productId
     * @param activity
     * @param
     */

    public void   getQRandBrandResouurceInfo(int brandId, String productId, final Activity activity, final  ArrayList<DownLoadInfo> downLoadInfos, final EpaperQRInfo qrInfo, final QrBook qrBook) {
        getQRandBrandResourceInfo(brandId, productId,
                new BaseExtCallBack(activity, EApplication.getInstance().getUserInfoBase().getUserId() + "") {
                    @Override
                    public void failed(int errorCode, Object data) {
                        super.failed(errorCode, data);
                        CWLog.w("Scan","  scan book jump failed<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<"+errorCode+data.toString());
                    }

                    @Override
                    public void failed(Object data) {
                        CWToast.makeText(activity, String.valueOf(data),
                                CWToast.LENGTH_LONG).show();
                        CWLog.w("Scan","  scan book jump failed<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<"+data.toString());
                    }

                    @Override
                    public void success(Object data) {
                        try {
                            List<EpaperInfo.Server> qrAndBrandInfos = (List<EpaperInfo.Server>) data;
                            CWLog.w("Scan","  scan book jump success<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<"+data.toString());

                            if (!qrAndBrandInfos.isEmpty()) {
                                if (qrBook != null) {
                                    //来自于扫书籍信息二维码
                                    EpaperInfo epaperInfo = new EpaperInfo();
                                    epaperInfo.setPackageId(qrBook.getPackageId() + "");
                                    epaperInfo.setBookIntro(qrBook.getBookIntro());
                                    epaperInfo.setCover(qrBook.getCover());
                                    epaperInfo.setGrade(qrBook.getGradeId());
                                    epaperInfo.setProductName(qrBook.getPackageName());
                                    epaperInfo.setPackageType(qrBook.getPackageType());
                                    epaperInfo.setPeriod(qrBook.getPeriodId());
                                    epaperInfo.setProductId(qrBook.getProductId() + "");
                                    epaperInfo.setSubjectId(qrBook.getSubjectId());
                                    epaperInfo.setServer(qrAndBrandInfos.get(0));
                                    CWLog.d("Scan","  scan  book   jump<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<");

                                    if (null != downLoadInfos) {
                                        CWLog.d("Scan","  scan  book   jumpdownLoadInfos<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<"+downLoadInfos.size());
                                    }

                                    EpaperJumpManager.jumpToCatalog(R.string.go_back, activity, epaperInfo, IntentValue.JumpToBookCatalogType.FROM_SCAN, -1, qrAndBrandInfos);

                                } else {
                                    if(qrInfo!=null&&qrInfo.getcType()==1){//new type
                                        CWLog.d("Scan","new  type  jump<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<");
                                        ScanJumpManager.jumpToNewTypeQrDetailAct(R.string.go_back, activity, downLoadInfos,  false);
                                    }else {
                                        CWLog.d("Scan","old  type  jump<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<");
                                        ScanJumpManager.jumpNewspaperQRInfo(R.string.go_back, activity, downLoadInfos, qrInfo!=null?qrInfo.getUrl():null, false, qrAndBrandInfos);
                                    }

                                }
                            } else {
                                CWLog.d("Scan","is no  data  jump<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<");
                                ScanJumpManager.jumpNewspaperQRInfo(R.string.go_back, activity, downLoadInfos, qrInfo!=null?qrInfo.getUrl():null, true, qrAndBrandInfos);
                            }
                        } catch (Exception e) {
                            e.printStackTrace();
                            Log.e("Scan",e.toString());
                            CWToast.makeText(activity, "无效数据！", CWToast.LENGTH_LONG)
                                    .show();
                        }
                    }
                }
        );
    }

    /**
     * 判断资源和品牌是否匹配
     *
     * @param brandId
     * @param productId
     * @param callBack
     */
    public void getQRandBrandResourceInfo(int brandId, String productId, BaseCallBack callBack) {
        ScanRequest.getQRandBrandResourceInfo(brandId, productId, callBack);
    }

    /**
     * 根据二维码获取电子报品牌信息
     *
     * @param url      二维码扫描出来的URL
     * @param callBack 回调
     */
    public void getQRNewspaperBrand(String url, final BaseCallBack callBack) {
        ScanRequest.getQRNewspaperBrand(url, callBack);
    }

    /**
     * 根据试卷编码获取试卷信息
     *
     * @param codeId   试卷编码
     * @param callBack 回调
     */
    public void paperCodeByInfo(int codeId, BaseCallBack callBack) {
        ScanRequest.paperCodeByInfo(codeId, callBack);
    }

    /**
     * 释放资源
     */
    public void release() {
        instance = null;
    }

}
